from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_POST
from django.utils import timezone
from apps.accounts.decorators import role_required
from apps.projects.models import Project
from apps.subprojects.models import SubProject
from .excel_utils import ExcelExporter, ExcelImporter
import io


@login_required
def export_projects_excel(request):
    """导出项目数据到Excel"""
    projects = Project.objects.all().order_by('-created_at')
    
    # 根据用户角色过滤数据
    if hasattr(request.user, 'userprofile'):
        if request.user.userprofile.role == 'college_user':
            projects = projects.filter(
                admin_manager__userprofile__college=request.user.userprofile.college
            )
    
    exporter = ExcelExporter()
    workbook = exporter.export_projects(projects)
    
    # 创建HTTP响应
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    
    filename = f"项目列表_{timezone.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
    response['Content-Disposition'] = f'attachment; filename="{filename}"'
    
    workbook.save(response)
    return response


@login_required
def export_subprojects_excel(request):
    """导出子项目数据到Excel"""
    subprojects = SubProject.objects.all().order_by('-created_at')
    
    # 根据用户角色过滤数据
    if hasattr(request.user, 'userprofile'):
        if request.user.userprofile.role == 'college_user':
            subprojects = subprojects.filter(
                project__admin_manager__userprofile__college=request.user.userprofile.college
            )
    
    exporter = ExcelExporter()
    workbook = exporter.export_subprojects(subprojects)
    
    # 创建HTTP响应
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    
    filename = f"子项目列表_{timezone.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
    response['Content-Disposition'] = f'attachment; filename="{filename}"'
    
    workbook.save(response)
    return response


@login_required
def download_project_template(request):
    """下载项目导入模板"""
    exporter = ExcelExporter()
    workbook = exporter.create_import_template('project')
    
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    
    response['Content-Disposition'] = 'attachment; filename="项目导入模板.xlsx"'
    workbook.save(response)
    return response


@login_required
def download_subproject_template(request):
    """下载子项目导入模板"""
    exporter = ExcelExporter()
    workbook = exporter.create_import_template('subproject')
    
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    
    response['Content-Disposition'] = 'attachment; filename="子项目导入模板.xlsx"'
    workbook.save(response)
    return response


@login_required
def import_projects_page(request):
    """项目导入页面"""
    return render(request, 'common/import_projects.html')


@login_required
def import_subprojects_page(request):
    """子项目导入页面"""
    return render(request, 'common/import_subprojects.html')


@login_required
@require_POST
def import_projects_excel(request):
    """导入项目数据"""
    if 'excel_file' not in request.FILES:
        return JsonResponse({
            'success': False,
            'message': '请选择要导入的Excel文件'
        })
    
    excel_file = request.FILES['excel_file']
    
    # 验证文件类型
    if not excel_file.name.endswith(('.xlsx', '.xls')):
        return JsonResponse({
            'success': False,
            'message': '请上传Excel文件（.xlsx或.xls格式）'
        })
    
    try:
        # 读取文件内容
        file_content = excel_file.read()
        
        # 导入数据
        importer = ExcelImporter(file_content)
        success = importer.import_projects()
        
        if success and importer.success_count > 0:
            message = f'成功导入 {importer.success_count} 个项目'
            if importer.errors:
                message += f'，{len(importer.errors)} 个错误'
            
            return JsonResponse({
                'success': True,
                'message': message,
                'success_count': importer.success_count,
                'errors': importer.errors
            })
        else:
            return JsonResponse({
                'success': False,
                'message': '导入失败',
                'errors': importer.errors
            })
    
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'文件处理错误：{str(e)}'
        })


@login_required
@require_POST
def import_subprojects_excel(request):
    """导入子项目数据"""
    if 'excel_file' not in request.FILES:
        return JsonResponse({
            'success': False,
            'message': '请选择要导入的Excel文件'
        })
    
    excel_file = request.FILES['excel_file']
    
    # 验证文件类型
    if not excel_file.name.endswith(('.xlsx', '.xls')):
        return JsonResponse({
            'success': False,
            'message': '请上传Excel文件（.xlsx或.xls格式）'
        })
    
    try:
        # 读取文件内容
        file_content = excel_file.read()
        
        # 导入数据
        importer = ExcelImporter(file_content)
        success = importer.import_subprojects()
        
        if success and importer.success_count > 0:
            message = f'成功导入 {importer.success_count} 个子项目'
            if importer.errors:
                message += f'，{len(importer.errors)} 个错误'
            
            return JsonResponse({
                'success': True,
                'message': message,
                'success_count': importer.success_count,
                'errors': importer.errors
            })
        else:
            return JsonResponse({
                'success': False,
                'message': '导入失败',
                'errors': importer.errors
            })
    
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'文件处理错误：{str(e)}'
        })


@login_required
def excel_management(request):
    """Excel导入导出管理页面"""
    context = {
        'project_count': Project.objects.count(),
        'subproject_count': SubProject.objects.count(),
    }
    return render(request, 'common/excel_management.html', context)